package vip.sweet.common.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectResponse;
import io.minio.UploadObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.sweet.common.config.MinioConfig;
import vip.sweet.common.service.CommonFileService;
import vip.sweet.common.service.CommonMinioService;

import java.io.InputStream;

/**
 * @author ASUS
 * @Date 2025/3/28 12:49
 * @Descripition
 */
@Service
public class CommonFileServiceImpl implements CommonFileService {
    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;
    @Resource
    private CommonMinioService commonMinioService;

    @Override
    public String uploadFile(MultipartFile file, String objectName) throws Exception {
        // 使用putObject上传一个文件到存储桶中。
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(objectName)
                .stream(inputStream, inputStream.available(), -1)
                .contentType(file.getContentType())
                .build());
        IoUtil.close(inputStream);
        return StrUtil.format("{}/{}/{}", minioConfig.getEndpoint(), minioConfig.getBucketName(), objectName);
    }

    @Override
    public boolean uploadObject(InputStream inputStream, String objectName, String contentType) throws Exception {
        minioClient.putObject(PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName).stream(
                        //不清楚文件的大小时，可以传-1，10485760。如果知道大小也可以传入size，partsize。
                        inputStream, -1, 10485760)
                .contentType(contentType)
                .build());
        IoUtil.close(inputStream);
        StatObjectResponse statObject = commonMinioService.getObjectInfo(minioConfig.getBucketName(), objectName);
        return statObject != null && statObject.size() > 0;
    }

    @Override
    public boolean uploadObject(String objectName, String fileName) throws Exception {
        minioClient.uploadObject(UploadObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(objectName)
                .filename(fileName)
                .build());
        StatObjectResponse statObject = commonMinioService.getObjectInfo(minioConfig.getBucketName(), objectName);
        return statObject != null && statObject.size() > 0;
    }
}
